package 线程;

import java.util.concurrent.Semaphore;

public class thread1to100 {
    // 线程

    // 定义两个信号量来控制线程的顺序  sem1 和sem2
    private static Semaphore semaphore1 = new Semaphore(1); // 控制线程1先打印
    private static Semaphore semaphore2 = new Semaphore(0); // 控制线程2等待

    public static void main(String[] args) {
        // 创建两个线程，分别打印1和2
        Thread thread1 = new Thread(new Printer(1, semaphore1, semaphore2));
        Thread thread2 = new Thread(new Printer(2, semaphore2, semaphore1));
        // 启动线程
        thread1.start();
        thread2.start();
    }

    // 打印数字的线程类
    static class Printer implements Runnable {
        private int number;
        private Semaphore mySemaphore;   // 当前线程的信号量
        private Semaphore nextSemaphore; // 下一个线程的信号量

        public Printer(int number, Semaphore mySemaphore, Semaphore nextSemaphore) {
            this.number = number;
            this.mySemaphore = mySemaphore;
            this.nextSemaphore = nextSemaphore;
        }

        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                try {
                    mySemaphore.acquire(); // 获取当前线程的信号量，确保按顺序执行
                    System.out.print(number + " "); // 打印当前数字
                    nextSemaphore.release(); // 释放下一个线程的信号量，允许下一个线程执行
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }
}
